package com.chat;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.chat.entity.DataPackage;
import com.chat.entity.ServerAction;
import com.chat.entity.User;
import com.chat.entity.event.ChannelEvent;
import com.chat.net.SocketClient;
import com.chat.ui.recyclerview.DetailFragment;
import com.google.android.material.navigation.NavigationView;
import com.theartofdev.edmodo.cropper.CropImage;

import io.netty.channel.Channel;

public class MainActivity extends AppCompatActivity {

    private AppBarConfiguration mAppBarConfiguration;
    public static Toolbar toolbar;
    public static MainActivity mainActivity;
    TextView textView;
    int GALLAY_CODE = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
        //获取用户信息并存储
        DataPackage dataPackage = DataPackage.request(ServerAction.GET_USER);
        SocketClient.getSocketClient().addChannelEvent(new ChannelEvent() {
            public void onChannelEvent(Channel ctx, DataPackage source) {
                if(source.getCode()==200){
                    User user = (User) source.getDate();
                    storeUser(user);
                }
            }
        },dataPackage);

        toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_home, R.id.nav_library, R.id.nav_slideshow,R.id.nav_recyclerview,R.id.nav_viewpaper)
                .setDrawerLayout(drawer)
                .build();

        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);

        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);
        mainActivity = this;
    }

    //存储用户信息
    public void storeUser(User user){
        SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("chat",MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt("userId",user.getUserId());
        editor.putString("userName",user.getName());
        editor.putString("account",user.getAccount());
        editor.apply();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        NavController navController= Navigation.findNavController(this,R.id.nav_host_fragment);
        int id=item.getItemId();
        if(id==R.id.action_settings&&navController.getCurrentDestination().getLabel().toString().equals("fragment_detail"))
        {
            Bundle bundle=new Bundle();
            bundle.putInt("id", DetailFragment.id);
            navController.navigate(R.id.nav_editbook,bundle);
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();
    }

    public void requestPermission(String permission){
        if (ContextCompat.checkSelfPermission(
                this, permission) ==
                PackageManager.PERMISSION_GRANTED) {
            Log.e("com.chat","获取权限成功！");
            // You can use the API that requires the permission.
//            performAction(...);
        } else if (shouldShowRequestPermissionRationale(permission)) {
            // In an educational UI, explain to the user why your app requires this
            // permission for a specific feature to behave as expected, and what
            // features are disabled if it's declined. In this UI, include a
            // "cancel" or "no thanks" button that lets the user continue
            // using your app without granting the permission.
//            showInContextUI(...);
        } else {
            // You can directly ask for the permission.
            // The registered ActizvityResultCallback gets the result of this request.
            requestPermissions(new String[]{permission},1);
//            requestPermissionLauncher.launch(
//                    Manifest.permission.REQUESTED_PERMISSION);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 &&
                        grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.e("com.chat","已经赋予权限了111！");
                    // Permission is granted. Continue the action or workflow
                    // in your app.
                }  else {
                    Log.e("com.chat","赋予权限失败了！");
                    // Explain to the user that the feature is unavailable because
                    // the feature requires a permission that the user has denied.
                    // At the same time, respect the user's decision. Don't link to
                    // system settings in an effort to convince the user to change
                    // their decision.
                }
                return;
        }
        // Other 'case' lines to check for other
        // permissions this app might request.
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);
            if (resultCode == GALLAY_CODE) {
                Uri resultUri = result.getUri();
                Log.e("com.chat",resultUri.toString());



            } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
                Exception error = result.getError();
            }
        }
    }
}
